package com.example.demo;

import com.example.demo.Client.Client;
import com.example.demo.Client.Send;
import com.example.demo.controller.ClientController;
import com.example.demo.dao.AccountMapper;
import com.example.demo.pojo.Account;
import com.example.demo.pojo.Friend;
import com.example.demo.pojo.Msg;
import com.example.demo.utils.MybatisUtils;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;

public class HelloController {
    @FXML
    private TextField account;
    @FXML
    private TextField password;


    @FXML
    protected void loginAction() throws IOException {
        SqlSession sqlSession = MybatisUtils.getSqlseesion();
        AccountMapper accountDao = sqlSession.getMapper(AccountMapper.class);
        Account account1 = accountDao.getAccountByAccountAndPassword(account.getText(),password.getText());
        if(account1 !=null){
            System.out.println(account1);
            Client client = new Client();
            client.startConnection("127.0.0.1",6666);
            Send send = new Send(client.getClientSocket());
            send.start();
            send.sendAccount(account1.getUsername());
            client.setAccount(account.getText());


            Stage stage = new Stage();
            FXMLLoader loader = new FXMLLoader(getClass().getResource("client.fxml"));
            Parent parent = loader.load();
            ClientController target = loader.getController();
            TableColumn<Msg, String> nameCol = new TableColumn<>("Commit");
            TableColumn<Friend, String> column = new TableColumn<>("Name");
            TableColumn<Friend, String> port = new TableColumn<>("Port");


            nameCol.setCellValueFactory(new PropertyValueFactory<>("msg"));
            column.setCellValueFactory(new PropertyValueFactory<>("username"));
            port.setCellValueFactory(new PropertyValueFactory<>("port"));
            target.username.setText(account1.getUsername());
            target.getCommit().getColumns().add(nameCol);
            target.getFriendList().getColumns().addAll(column,port);

            target.setClient(client);
            target.setSend(send);
            send.setClientController(target);

            Scene scene = new Scene(parent);
            stage.setScene(scene);
            stage.show();
            Stage primaryStage = (Stage) account.getScene().getWindow();
            primaryStage.hide();
        }
    }
}